package com.temdemo.utils.SnapPay;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class HttpPostUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpPostUtils.class);
    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static String doPost(String url,String params) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        HttpEntity entity = new StringEntity(params, ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(entity);
        try {
            CloseableHttpResponse resp = httpClient.execute(httpPost);
            int httpRc = resp.getStatusLine().getStatusCode();
            if (httpRc == 200) {
                InputStream inputStream = resp.getEntity().getContent();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                String mapJson = result.toString(StandardCharsets.UTF_8.name());
                return mapJson;
            }
        } catch (IOException e) {
            logger.error("调用异常 !");
            e.printStackTrace();
        }
        return null;
    }
}
